import {defineConfig, loadEnv} from 'vite'
import {createHtmlPlugin} from 'vite-plugin-html'
import tailwindcss from "@tailwindcss/vite"
import vue from '@vitejs/plugin-vue'
import path from 'path' // Node 内置模块，用于处理路径
import fs from 'fs'

const srcPath = path.resolve(__dirname, './src') + '/';
const basePath = path.resolve(__dirname) + '/';
const buildFileName = (assetInfo) => {
    let file = '';
    if (assetInfo.type == 'asset') {
        file = '[name][extname]?id=[hash]';
        if (assetInfo.originalFileNames && assetInfo.originalFileNames[0]) {
            file = assetInfo.originalFileNames[0] + '[extname]?id=[hash]';
            if (file.startsWith('src/')) {
                file = file.substring(4);
            }
        }
    } else if (assetInfo.type == 'chunk') {
        file = '[name].js?id=[hash]';
        if (assetInfo.facadeModuleId) {
            file = assetInfo.facadeModuleId + '.js?id=[hash]';
            if (file.startsWith(srcPath)) {
                file = file.substring(srcPath.length);
            } else if (file.startsWith(basePath)) {
                file = file.substring(basePath.length);
            }
        }
    } else {
        file = '[name].js?id=[hash]';
    }

    const extType = assetInfo.name.split('.').pop();
    // 将图片文件放到 images 目录
    if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'].includes(extType)) {
        return `assets/images/${file}`;
    }
    // 将字体文件放到 fonts 目录
    if (['ttf', 'woff', 'woff2', 'eot'].includes(extType)) {
        return `assets/fonts/${file}`;
    }
    // CSS文件单独存放
    if (extType === 'css') {
        return `assets/css/${file}`;
    }
    // 其他资源统一放在 assets 目录
    return `assets/js/${file}`;
}

// 自定义插件，用于在构建完成后重命名文件
const renameFilesPlugin = () => {
    return {
        name: 'vite-plugin-rename-files',
        apply: 'build', // 仅在生产构建时应用:cite[1]

        // 使用 closeBundle 钩子，它在构建过程完全结束、资源已写入磁盘后触发:cite[1]
        closeBundle: async () => {


// 递归处理目录中的文件
            async function processFiles(directory) {
                const items = await fs.promises.readdir(directory, {withFileTypes: true});


                for (const item of items) {
                    const fullPath = path.join(directory, item.name);

                    if (item.isDirectory()) {
                        // 如果是目录，则递归处理
                        await processFiles(fullPath);
                    } else if (item.isFile()) {
                        // 如果是文件，则检查并重命名
                        await renameFile(fullPath);
                    }
                }
            }

// 重命名单个文件，去除 ? 及后面的查询参数
            async function renameFile(filePath) {
                const dirName = path.dirname(filePath);
                const fileName = path.basename(filePath);

                // 使用正则表达式匹配文件名中 ? 及之后的内容，并将其移除
                // 例如将 `index.html?a1b2c3` 重命名为 `index.html`
                const newFileName = fileName.replace(/\?[^?]*$/, ''); // 确保在文件扩展名之前操作:cite[10]
                if (newFileName !== fileName) {
                    const newFilePath = path.join(dirName, newFileName);
                    try {
                        await fs.promises.rename(filePath, newFilePath);
                        //console.log(`已重命名: ${fileName} -> ${newFileName}`);
                    } catch (renameError) {
                        console.error(`重命名文件 ${filePath} 失败:`, renameError);
                    }
                }
            }

            const distPath = path.resolve(process.cwd(), 'dist'); // 默认构建输出目录，可根据你的配置调整
            console.log('构建完成，开始处理文件命名...');
            console.log('重命名文件名目录:' + distPath);
            try {
                await processFiles(distPath);
                console.log('文件重命名处理完成。');
            } catch (error) {
                console.error('在处理文件时发生错误:', error);
            }
        }
    };
};

export default ({mode}) => {
    // 加载环境变量
    const env = loadEnv(mode, process.cwd())
    let api_base_url = env.VITE_API_BASE_URL || ''
    let prefix = env.VITE_WEB_API_MODEL == 'api' ? '/api' : '/web-api'
    return defineConfig({
        publicDir: 'public',
        plugins: [
            tailwindcss(),
            vue(),
            createHtmlPlugin({
                inject: {
                    data: {
                        api_base_url: api_base_url + prefix,
                        build_time: JSON.stringify(new Date().getTime())
                    }
                }
            }),
            renameFilesPlugin(),
        ],
        resolve: {
            // 配置路径别名
            alias: {
                '@': path.resolve(__dirname, './src'), // 将 @ 指向 src 目录
                'components': path.resolve(__dirname, './src/components'), // 直接映射到 components 目录
                'common_components': path.resolve(__dirname, './src/components'),
                "page_components": path.resolve(__dirname, './src/pages/components'),
                "pages": path.resolve(__dirname, './src/pages'),
            }
        },
        build: {
            chunkSizeWarningLimit: 1024, // 警告提醒提高到1MB
            rollupOptions: {
                output: {
                    assetFileNames: buildFileName,
                    entryFileNames: buildFileName,
                    chunkFileNames: buildFileName,
                    // 对node_modules中的依赖进行分包
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            const chunk = id.toString().split('node_modules/')[1].split('/');
                            let chunkName = chunk[0].toString();
                            let chunkSecondary = chunk[1].toString();
                            if (['@fortawesome'].includes(chunkName)) {
                                if (chunkSecondary.startsWith('free-')) {
                                    return '@fortawesome/' + chunkSecondary;
                                }
                            }
                            //开启检测每个包对应大小方便拆包
                            //return chunkName+'/'+chunkSecondary;
                        }
                    }
                }
            }
        }
    })
}

